package com.jse.mvc;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.nutz.json.Json;
import org.nutz.lang.Times;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.Mvcs;

/**
 * @author Arun Gupta
 */
@MultipartConfig(maxFileSize=1024*1024*100,maxRequestSize=1024*1024*100,fileSizeThreshold=0)
@WebServlet(name = "uploadServlet", urlPatterns = "/upload/file")
public class UploadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private static Log log = Logs.get();

	/**
	 * Handles the HTTP <code>POST</code> method.
	 *
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 * @throws ServletException
	 *             if a servlet-specific error occurs
	 * @throws IOException
	 *             if an I/O error occurs
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");  
        response.setContentType("application/json; charset=UTF-8");  
        PrintWriter out = response.getWriter();  
        //Servlet3.0中新引入的方法，用来处理multipart/form-data类型编码的表单  
        Part part = request.getPart("file");  
        //获取HTTP头信息headerInfo=（form-data; name="file" filename="文件名"）  
        String headerInfo = part.getHeader("content-disposition");  
        //从HTTP头信息中获取文件名fileName=（文件名）  
        String fileName = headerInfo.substring(headerInfo.lastIndexOf("=") + 2, headerInfo.length() - 1);  
        String prefix = fileName.substring(fileName.lastIndexOf("."));//后缀
        String fid = UUID.randomUUID().toString();
        //获得存储上传文件的文件夹路径  
		String str = Mvcs.getServletContext().getRealPath("/").replace("\\", "/");
		String appName = str.substring(0, str.lastIndexOf("/"));
		appName = appName.substring(appName.lastIndexOf("/"));
		String webPath = str.substring(0, str.indexOf("tomcat") + 7) + "webapps/";
		String filePath = str.substring(0, str.indexOf("tomcat") + 7) + "webapps/upload" + appName +
				"/file/"+Times.format("yyyyMMdd",new Date())+"/";
        //获得存储上传文件的完整路径（文件夹路径+文件名）  
        //文件夹位置固定，文件夹采用与上传文件的原始名字相同  
        String fileSavingPath = filePath+fid+prefix;  
        //如果存储上传文件的文件夹不存在，则创建文件夹  
        File f = new File(filePath);  
        if(!f.exists()){  
            f.mkdirs();  
            
        }  
        //将上传的文件内容写入服务器文件中  
        part.write(fileSavingPath);  
        log.infof("file save %s",fileSavingPath);
        //输出上传成功信息  
        String newfilePath = fileSavingPath.replace(webPath, "");
        NutMap map=new NutMap();
        map.put("id", fid);
        map.put("path", newfilePath);
        map.put("name", fileName);
        map.put("file", fileSavingPath);
        map.put("msg", "success");
        out.println(Json.toJson(map));
	}

}
